<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>冒泡排序</h1>
    <img src="./image/maopao.gif" alt="">
    <h1>快速</h1>
    <img src="./image/quickSort.gif" alt="">
    <h1>插入排序</h1>
    <img src="./image/insertSort.gif" alt="">
    <h1>选择排序</h1>
    <img src="./image/selectSort.gif" alt="">
    <p><a href="https://visualgo.net/en/sorting" target="new_black">算法可视化排序</a></p>
    
<script>
   var arr = [1,66,7,12,10,2];
   //冒泡排序
   function maoSort(arr){
      for (var i = 0; i < arr.length; i++) {
          for (var j = i+1; j < arr.length; j++) {
              if (arr[i] > arr[j] ) {
                  var temp = arr[i]
                  arr[i] = arr[j];
                  arr[j] = temp
              }
          } 
      }
      return arr
   }
   //console.log(maoSort(arr))
   //快速排序
   function quickSort(arr){
       //条件
       if (arr.length <= 1) {
           return arr
       }
       var arr = arr;
       var middleIndex = Math.floor((arr.length-1) / 2); //中间下标
       var middleValue = arr[middleIndex]; //中间值
       arr.splice(middleIndex,1);
       var left = [],right = []; //生命左右两个数组
       for (var i = 0; i < arr.length; i++) {
           if (middleValue > arr[i]) {
               left.push(arr[i])
           }else{
               right.push(arr[i])
           }
       }
       return quickSort(left).concat(middleValue,quickSort(right))
   }
   //console.log(quickSort(arr))
   //插入排序
   function insertSort(arr){
       for (var i = 1; i < arr.length; i++) {
           var preIndex = i-1;
           var currentValue = arr[i];
           while(arr[preIndex] > currentValue && preIndex >= 0){
                arr[preIndex +1 ] = arr[preIndex];
                preIndex--
           }
           if (preIndex + 1 != i) {
               arr[preIndex + 1] = currentValue
           }
       }
       return arr
   }
   console.log(insertSort(arr))
   //选择排序 [  ]
   function selectionSort(arr) {
        var len = arr.length;
        var minIndex, temp;
        for (var i = 0; i < len - 1; i++) {
            minIndex = i;
            for (var j = i + 1; j < len; j++) {
                if (arr[j] < arr[minIndex]) {     //寻找最小的数
                    minIndex = j;                 //将最小数的索引保存
                }
            }
            temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
        return arr;
    }
    console.log(selectionSort([1,4,6,22,7,2,3]))
</script>
</body>
</html>